package store.lunangangster.engine.impl.cmd;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import store.lunangangster.engine.NodeFlowException;
import store.lunangangster.engine.impl.entity.ExecutionEntity;
import store.lunangangster.engine.impl.entity.mgr.ExecutionEntityManager;
import store.lunangangster.engine.impl.interceptor.CommandContext;

public class GetVariablesCmd implements Command<Map<String, Object>> {

  protected Collection<String> variableNames;
  protected String executionId;
  protected boolean getAll;

  public GetVariablesCmd(String executionId) {
    this(null, executionId);
    this.getAll = true;
  }

  public GetVariablesCmd(Collection<String> variableNames, String executionId) {
    this.variableNames = variableNames;
    this.executionId = executionId;
    this.getAll = false;
  }

  @Override
  public Map<String, Object> execute(CommandContext commandContext) {
    if (!getAll && (variableNames == null || variableNames.isEmpty())) {
      throw new NodeFlowException("variableNames不能为空");
    }
    if (StringUtils.isBlank(executionId)) {
      throw new NodeFlowException("executionId不能为空");
    }
    ExecutionEntityManager executionManager = commandContext.getProcessEngineConfiguration()
        .getExecutionEntityManager();
    ExecutionEntity executionEntity = executionManager.selectById(executionId);
    Map<String, Object> variables = executionEntity.getVariables();
    if (getAll) {
      return variables;
    }
    Map<String, Object> result = new HashMap<>(variableNames.size());
    variableNames.forEach(name -> {
      if (variables.containsKey(name)) {
        result.put(name, variables.get(name));
      }
    });
    return result;
  }
}
